export {}

console.log("Background loading")

// 监听来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'uploadFile') {
    // 处理文件上传请求
    handleFileUpload(request.data)
      .then(response => {
        sendResponse({ success: true, data: response });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    
    // 返回true表示异步响应
    return true;
  }
});

// 处理文件上传的函数
async function handleFileUpload(uploadData: any) {
  console.log('uploadData:', uploadData);
  const { url, input_xpath,formData } = uploadData;


  try {
    // 创建FormData
    const form = new FormData();
    
    // 添加文件数据
    if (uploadData.fileData) {
      // 将base64数据转换为Blob
      const byteCharacters = atob(uploadData.fileData.split(',')[1]);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: uploadData.fileType });
      
      form.append('file', blob, uploadData.fileName);
      form.append('input_xpath',input_xpath);
    }
    
    // 添加其他表单数据
    if (formData) {
      Object.keys(formData).forEach(key => {
        form.append(key, formData[key]);
      });
    }
    
    // 发送请求
    const response = await fetch(url, {
      method: 'POST',
      body: form
    });
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const result = await response.json();
    return result;
    
  } catch (error) {
    console.error('Background script upload error:', error);
    throw error;
  }
}
